import { Clock } from '$lib/clock';
import { Collision, Creature, Description, Glyph, Impassable, Player, Size } from '$lib/components';
import { Heart } from '$lib/content/heart';
import { Eyes } from '$lib/eyes';
import { VisualMemory } from '$lib/memory';
import { hasComponent } from '$lib/ecs';
import { Hunger } from './hunger';
import { Evasion, Precision, HP } from './stats';
import { NeedSwim, Passage } from './ground';
import { Move3Action } from '$lib/walk3';
import { Ground } from '$lib/content/ground';
import { Surface } from './ship';

export const moleTemplate = [
  [Creature],
  [Player],
  [Description, {
    summary: 'mole',
    description: "That's you",
  }],
  [Glyph, {
    glyph: '@',
    color: '#fff',
  }],
  [Collision],
  [Size, {
    size: 4,
  }],
  [Clock],
  [VisualMemory],
  [Heart, {
    heartbeat: 10,
    elapsed: 0,
  }],
  [Eyes, {
    range: 5,
  }],
  [HP, {
    maxhp: 3,
    hp: 3,
  }],
  [Hunger, {
    satiation: 0,
    tick: 1,
  }],
  [Precision, {
    amount: 10,
  }],
  [Evasion, {
    amount: 20,
  }],
];

export const doesntCollideWithMole = (world, e) =>
  (!hasComponent(world, Collision, e) && !hasComponent(world, Impassable, e))
  || hasComponent(world, Passage, e);

export const moleCanPass = (world, es) => {
  const hasCreature = es.some((e) => hasComponent(world, Creature, e));
  if (hasCreature)
    return false;
  const groundPass = es.some((e) =>
    (hasComponent(world, Ground, e) &&
      (hasComponent(world, Passage, e) || !hasComponent(world, NeedSwim, e))) ||
    hasComponent(world, Surface, e));
  return groundPass;
};

export const MoleMove = (dx, dy, dz) => (world, e) => {
  const delay = Heart.heartbeat[e];
  return Move3Action(moleCanPass)(dx, dy, dz, delay)(world, e);
};
